<template>
	<!-- 图片上传到云空间 -->
	<view class="app">
		<view v-if="!!formData.id" class="" style="margin: 6px 0;font-size:1.4em;font-weight: 700;text-align: center;">单位名称： {{formData.username || ''}}</view>
		
		<view v-if="!formData.id" class="" style="margin: 6px 0;font-size:1.2em;color: red;">
			尚未填写申报信息，请点击“上一步”，去填写申报信息。
		</view>
		<view v-else-if="!disabledInput" class="" style="font-size:1.2em;">
			<view class="">请点击“下载”按钮，下载《辽宁省餐饮服务单位量化分级等级评定申报表》和《承诺书》，签字盖章后重新回到本页面上传照片。</view>
			<view class="" style="padding-top:10px;">
				默认密码 <text style="font-size:20px;font-weight:700;color:red;">123456</text> ，
				<text style="font-weight:700;">请牢记！</text>
				重新回到本页面上传照片，需要输入<text style="font-weight:700;"> 许可证号 </text>和<text style="font-weight:700;"> 密码 </text>来核对您的申报信息。
			</view>
		</view>
		<view v-else class="" style="font-size:1.3em; text-align: center; margin-top: 40px;">已完成申报，请等待评审员与您联系。
			
			<view class="" style="margin-top: 18px;"> 您还可以
				<u-button type="primary" size="mini" shape="square" @click="showDate = true"> 预约现场评定日期 </u-button>
			</view>
			<view class="" style="text-align: center;" v-if="yuyuedate">
				您已预约 <text style="font-size:20px;font-weight:700;color:red;">{{yuyuedate}}</text> 进行现场评定
			</view>
		</view>
		
		<u-calendar v-model="showDate" mode="date" :min-date="minDate" :max-date="maxDate"  @change="changeDate"></u-calendar>
		
		<u-form v-if="!disabledInput" :model="formData" ref="uForm" :error-type="errorType" label-position="top">
			<u-form-item prop="images1" label="上传《辽宁省餐饮服务单位量化分级等级评定申报表》并加盖公章的照片" required>
				<htz-image-upload :sourceType="['album', 'camera']" mediaType="image" max="1"
					v-model="imgs1" :action="uploadAction">
				</htz-image-upload>
				<u-input ref="images1" style='display: none;' v-model="formData.images1" />
				<u-button v-show="!!formData.id" type="primary" size="medium" shape="square" @click="toWord(1)">下载《申报表》</u-button>
			</u-form-item>			
			<u-form-item prop="images2" label="上传《承诺书》照片" required>
				<htz-image-upload :sourceType="['album', 'camera']" mediaType="image" max="1"
					v-model="imgs2" :action="uploadAction">
				</htz-image-upload>
				<u-input style='display: none;' v-model="formData.images2" />
				<u-button v-show="!!formData.id" type="primary" size="medium" shape="square" @click="toWord(2)">下载《承诺书》</u-button>
			</u-form-item>
			<u-form-item prop="images3" label="上传营业执照 或 法人证书 或 社会服务机构登记证书复印件照片" required>
				<htz-image-upload :sourceType="['album', 'camera']" mediaType="image" :max="maxPicCounts"
					v-model="imgs3" :action="uploadAction">
				</htz-image-upload>
				<u-input style='display: none;' v-model="formData.images3" />
			</u-form-item>
			<u-form-item prop="images4" label="上传食品经营许可证照片" required>
				<htz-image-upload :sourceType="['album', 'camera']" mediaType="image" :max="maxPicCounts"
					v-model="imgs4" :action="uploadAction">
				</htz-image-upload>
				<u-input style='display: none;' v-model="formData.images4" />
			</u-form-item>
		</u-form>
		<view class="btn-bar" v-if="!disabledInput">
			<u-button v-if="!!formData.id" type="primary" shape="square" :loading="loading" :disabled="disabled" @click="submit">提交</u-button>
			<!-- <u-button v-else type="primary" shape="square" @click="toPage('./form')">上一步</u-button> -->
			<view class="loginBtn" v-if="!formData.id">
				<u-button type="info" shape="square" size="medium" @click="toPage('./form')">上一步</u-button>
				<u-button type="primary" shape="square" size="medium" @click="showLoginForm = true">去登录</u-button>
			</view>
		</view>
		
		<!-- <u-popup v-model="showLoginForm" width="600rpx" height="400rpx" border-radius="18">
			<view>
				<view class="loginTitle">登录获取申报的企业</view>
				<view class="loginForm">
					<u-field style="width: 100%;"
						v-model="xkz"
						label="许可证号"
						placeholder="请填写许可证号"
						trim
						:field-style="fieldStyle"
						:error-message="errorMessage1"
					/>
					<u-field style="width: 100%;"
						v-model="pwd"
						label="密码"
						placeholder="请填写密码"
						trim
						:field-style="fieldStyle"
						:error-message="errorMessage2"
					/>
				</view>
				<view class="loginBtn">
					<u-button type="info" shape="square" size="medium" @click="toPage('./form')">上一步</u-button>
					<u-button type="primary" shape="square" size="medium" :loading="loading" :disabled="disabled" @click="login">登录</u-button>
				</view>
			</view>
		</u-popup> -->
			
		<u-mask :duration="10":show="showLoginForm" z-index="1000" @click="showLoginForm=false"></u-mask>
		<view class="loginDialog" v-show="showLoginForm">
			<view class="loginTitle">登录获取申报的企业</view>
			<view class="loginForm">
				<u-field style="width: 100%;"
					v-model="xkz"
					label="许可证号"
					placeholder="请填写许可证号"
					trim
					:field-style="fieldStyle"
					:error-message="errorMessage1"
				/>
				<u-field style="width: 100%;"
					v-model="pwd"
					label="密码"
					placeholder="请填写密码"
					trim
					:field-style="fieldStyle"
					:error-message="errorMessage2"
				/>
			</view>
			<view class="loginBtn">
				<u-button type="info" shape="square" size="medium" @click="toPage('./form')">上一步</u-button>
				<u-button type="primary" shape="square" size="medium" :loading="loading" :disabled="disabled" @click="login">登录</u-button>
			</view>
		</view>
	</view>
</template>

<script>
	import config from '@/app.config.js'
	
	export default {
		data() {
			let formData = {
				images1: '',
				images2: '',
				images3: '',
				images4: '',
			};
			return {
				disabled: false, // 提交中
				loading: false, // 提交中
				
				id: '',
				formData,
				
				showLoginForm: false,
				xkz: '',
				pwd: '',
				errorMessage1: '',
				errorMessage2: '',
				fieldStyle: {
					color: '#30616C',
					letterSpacing: '1rpx'
				},
				
				yuyuedate: null,
				showDate: false,
				minDate: vk.pubfn.timeFormat(new Date(), "yyyy-MM-dd"),
				maxDate: '2050-12-31', // 日历的最大可选日期
				
				rules: {
					"images1": [{
						"required": true,
						message: '请上传《辽宁省餐饮服务单位量化分级等级评定申报表》并加盖公章的照片',
						trigger: ['change', 'blur'],
					}],
					"images2": [{
						"required": true,
						message: '请上传《承诺书》照片',
						trigger: ['change', 'blur'],
					}],
					"images3": [{
						"required": true,
						message: '请上传营业执照、法人证书或社会服务机构登记证书复印件照片',
						trigger: ['change', 'blur'],
					}],
					"images4": [{
						"required": true,
						message: '请上传食品经营许可证照片',
						trigger: ['change', 'blur'],
					}],
				},
				// 文字和下划线提示
				errorType: ['message', 'border-bottom'],
				placeholderStyle: "",
				styles: {},
				disabledInput: false,
				
				// 图片上传
				imgs1: [],
				imgs2: [],
				imgs3: [],
				imgs4: [],
				// 文件下载
				doc1: '',
				doc2: '',
				
				// // 图片上传
				uploadAction: 'uniCloud', // 上传到云空间
				// uploadFormData: { },
				// uploadName: 'image',
				// minPicCounts: 1, // 至少上传1张照片
				maxPicCounts: 3, // 最多上传9张照片 3
			}
		},
		onLoad(options) {
			this.initPage(options);
		},
		onReady() {
			this.$refs.uForm.setRules(this.rules);
		},
		methods: {
			initPage(options = {}){
				this.id = options.id
				this.getInfo(); // 在方法里判断id走不同分支
			},
			toPage(url) {
				vk.navigateTo(url)
			},
			// 获取详情
			getInfo(){
				let url, data;
				if(this.id){
					url = 'client/sakj/pub.lhfj.getApplyInfoById';
					data = { id: this.id }
				}else{
					this.showLoginForm = true;
					return
				}
				vk.callFunction({
					url,
					data
				})
				.then(res => {
					// console.log('getInfo res', res)
					if(res.code === 0 && res.data){
						this.formData = res.data;
						this.imgs1 = this.formData.images1 ? this.formData.images1.split(",") : [];
						this.imgs2 = this.formData.images2 ? this.formData.images2.split(",") : [];
						this.imgs3 = this.formData.images3 ? this.formData.images3.split(",") : [];
						this.imgs4 = this.formData.images4 ? this.formData.images4.split(",") : [];
						
						this.disabledInput = this.formData.images1 && this.formData.images2 && this.formData.images3 && this.formData.images4
					}
				})
				.catch(err => {console.log('getInfo err', err)})
			},
			// 登录。仅为了获取申报信息，不保留登录状态
			login(){
				this.errorMessage1 = this.xkz ? '' : '请输入许可证号';
				this.errorMessage2 = this.pwd ? '' : '请输入密码'
				
				if(this.errorMessage1 || this.errorMessage2){
					return
				}
				
				let url, data;
				url = 'client/sakj/pub.lhfj.getApplyInfoByXkzAndPwd';
				data = { xkz: this.xkz, pwd: this.pwd }
				
				vk.callFunction({
					url,
					data
				})
				.then(res => {
					// console.log('login res', res)
					if(res.code === 0 && res.data){
						this.formData = res.data;
						this.imgs1 = this.formData.images1 ? this.formData.images1.split(",") : [];
						this.imgs2 = this.formData.images2 ? this.formData.images2.split(",") : [];
						this.imgs3 = this.formData.images3 ? this.formData.images3.split(",") : [];
						this.imgs4 = this.formData.images4 ? this.formData.images4.split(",") : [];
						
						this.disabledInput = this.formData.images1 && this.formData.images2 && this.formData.images3 && this.formData.images4
						this.id = this.formData.id;
						this.showLoginForm = false;
						this.errorMessage1 = '';
						this.errorMessage2 = '';
						
						this.yuyuedate = this.formData.yuyuedate
						
					}else{
						this.errorMessage1 = '未查询到该企业本年度的申报信息'
					}
				})
				.catch(err => {console.log('login err', err)})
			},
			/**
			 * 验证表单并提交
			 */
			submit(e) {
				if (config.debug) console.log('验证表单', this.formData)
				
				this.formData.images1 = this.imgs1.toString();
				this.formData.images2 = this.imgs2.toString();
				this.formData.images3 = this.imgs3.toString();
				this.formData.images4 = this.imgs4.toString();
				
				this.disabled = true;
				this.loading = true;
				
				let that = this
				
				setTimeout(function(){
					that.formValid()
				}, 100)
			},
			formValid(){
				this.$refs.uForm.validate(valid => {
					if (config.debug) console.log('验证valid', valid)
					if (valid) {
						this.submitForm()
					} else {
						this.disabled = false;
						this.loading = false;
					}
				});
			},
			submitForm() {
				vk.callFunction({
					url: 'client/sakj/pub.lhfj.apply2',
					data: this.formData
				})
				.then(res => {
					if (config.debug) console.log('提交res', res);
					vk.toast("提交成功", "none", () => {
						this.loading = false;
						uni.setStorageSync('companyId', this.formData.id)
						uni.setStorageSync('companyYuyue', this.formData.yuyuedate)
						vk.reLaunch('./success')
					}); 
				})
				.catch(err => {
					if (config.debug) console.log('提交err', err);
					this.disabled = false;
					this.loading = false;
				})
			},
			
			// 更换日历
			changeDate(e) {
				this.yuyuedate = e.result
				this.submitDate();
			},
			submitDate() {
				let data = {
					id: this.id,
					yuyuedate: this.yuyuedate
				}
				// console.log('提交data', data);
				vk.callFunction({
					url: 'client/sakj/pub.lhfj.apply3',
					data
				})
				.then(res => {
					// console.log('预约res', res);
					vk.toast("预约成功，请等待工作人员受理", "none", () => {
						
					}); 
				})
				.catch(err => {
					console.log('提交err', err);
				})
			},
			// wordData是模板需要的数据
			// 图片需要转base64才能在word显示
			async toWord(flag) {
				// console.log('==== toWord', flag)
				/*
				1	《辽宁省餐饮服务单位量化分级等级评定申报表》
				2	《承诺书》
				*/
				let downFileName = '';  // 下载显示的文件名
				let templateName = '';  // 模板文件名
				let wordData = {}; //模板参数
				let code = ''; // 编号，主要用于上传云空间的文件名
				
				if(flag == 1){
					downFileName = '辽宁省餐饮服务单位量化分级等级评定申报表';
					templateName = 'shenbaobiao.docx'
					wordData = {
						userno             : this.formData.userno           ,
						xukezhenghao       : this.formData.xukezhenghao     ,
						username           : this.formData.username         ,
						faren              : this.formData.faren            ,
						farentel           : this.formData.farentel         ,
						jingyingdizhi      : this.formData.jingyingdizhi    ,
						lianxiren          : this.formData.lianxiren        ,
						lianxirentel       : this.formData.lianxirentel     ,
						personQuantity     : this.formData.personQuantity   ,
						fsd                : this.formData.fsd              ,
						fsd00              : this.formData.fsd!='0'         ,
						fsd01              : this.formData.fsd=='0'         ,
						fsd10              : this.formData.fsd!='1'         ,
						fsd11              : this.formData.fsd=='1'         ,
						fsdName            : this.formData.fsdName || ' '    ,
						fsdTel             : this.formData.fsdTel || ' '     ,
						operatingArea      : this.formData.operatingArea    ,
						cuisine            : this.formData.cuisine || ' '          ,
						jianguanjiguan     : this.formData.jianguanjiguan || ' '   ,
						jianguanjiguantel  : this.formData.jianguanjiguantel || ' ',
						danweijieshao      : this.formData.danweijieshao    ,
					}
					code = 'lhfj_shenbaobiao_' + this.formData.id
				}else if(flag == 2){
					downFileName = '承诺书';
					templateName = 'chengnuoshu.docx'
					wordData = {username: this.formData.username}
					code = 'lhfj_chengnuoshu_' + this.formData.id
				}
				
				if(this['doc' + flag]){
					this.download(downFileName + '.docx', this['doc' + flag])
					return 
				}else{
					vk.callFunction({
							url: 'common/pub.docxtemplater.genDocx',
							loading: true,
							data: {
								code,  // 编号，主要用于上传云空间的文件名
								templateName,  // word模板名 xxx.docx 。 word模板在admin项目的云服务router/service/common中
								wordData,  // 模板中的参数集合
							}
						})
						.then(res => {
							// console.log('生成word res', res)
							this['doc' + flag] = res.fileUrl;
							this.download(downFileName + '.docx', this['doc' + flag])
						})
				}
			},
			// 下载文件
			download(filename, url) {
				// #ifdef H5
				window.open(url)
				// #endif
				
				// 微信下载文件需要在微信公众平台>开发>开发管理>服务器域名>downloadFile合法域名>配置白名单域名
				// #ifdef MP-WEIXIN
				uni.downloadFile({
					url,
					success: res => {
						// console.log('下载成功', res)
						if (res.statusCode === 200) {
							let tempFilePath = res.tempFilePath; // 临时路径
			
							// 重命名，以免用户下载的文件是乱码
							let suffix = tempFilePath.substr(tempFilePath.lastIndexOf('.'), tempFilePath
								.length - 1)
							// let filePath = wx.env.USER_DATA_PATH + '/' + filename + suffix;
							let filePath = wx.env.USER_DATA_PATH + '/' + filename;
			
							// 文件保存到本地
							uni.getFileSystemManager().saveFile({
								tempFilePath, // 源文件临时路径
								filePath, // 新的文件路径
								success: function(res1) {
									uni.showToast({
										icon: 'none',
										mask: true,
										title: '文件已保存!',
										duration: 2000,
									});
									// 打开文件
									uni.openDocument({
										showMenu: true, // 显示右上角3个点，可以进行转发、保存等操作
										filePath: res1.savedFilePath,
										success: function(res2) {
											// console.log('打开文档成功');
										}
									});
								}
							});
						}
					}
				})
				// #endif
			},
		}
	}
</script>

<style>
.photo-bg {
	position: relative;
    width: 80px;
    height: 80px;
    border: 1px solid RGB(204, 204, 204);
}
.photo-plus{
	position: absolute;
	top: 0;
	left: 0;
	z-index: 100;
	content: '+';
	width: 80px;
	height: 80px;
	font-size: 64px;
	line-height: 60px;
	text-align: center;
	color: #e1e1e1;
}
/* .photo-bg::before{
	position: absolute;
	top: 0;
	left: 0;
	z-index: 100;
	content: '+';
	width: 80px;
	height: 80px;
	font-size: 100px;
	line-height: 60px;
	text-align: center;
	color: RGB(204, 204, 204);
} */
.photo-img{
	position: absolute;
	top: 0;
	left: 0;
	z-index: 101;
	width: 80px;
	height: 80px;
}

.loginDialog{
	position: fixed;
	top: 300rpx;
	left: 0;
	right: 0;
	margin: auto;
	width: 600rpx;
	height: 500rpx;
	background-color: #fff;
	border-radius: 18px;
	box-shadow: 1px 1px 2px 2px #000;
	transition: all 0.25s linear;
	z-index: 1001;
}
.loginTitle{
	padding-top: 60rpx;
	font-size: 16px;
	text-align: center;
}
.loginForm{
	padding: 20rpx 30rpx 50rpx;
	display: flex;
	flex-direction: column;
	width: 100%;
}
.loginBtn{
	display: flex;
	justify-content: space-around;
}
</style>
